package com.zmc.order.infrastructure.updater.order;

import com.alibaba.fastjson.JSON;
import com.zmc.common.exception.base.BusinessException;
import com.zmc.order.infrastructure.entity.MerchantOrderEntity;
import com.zmc.order.infrastructure.entity.OrderEntity;
import com.zmc.order.infrastructure.enums.OrderEnum;
import com.zmc.order.infrastructure.service.MerchantOrderService;
import com.zmc.order.infrastructure.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author：zmc
 * @Date：2025/5/15 18:01
 * 订单确认发货
 */
@Component
public class OrderConfirmShipmentUpdater<T> implements OderUpdater<T> {

    public static Logger log = LoggerFactory.getLogger(OrderConfirmShipmentUpdater.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private MerchantOrderService merchantOrderService;

    @Override
    @Transactional
    public void execute(T param) {
        //商户订单号
        String orderSn = (String) param;
        MerchantOrderEntity merchantOrder = merchantOrderService.getByOrderSn(orderSn);
        if (merchantOrder == null) {
            log.error("订单发货异常：orderSn:{} 不存在", orderSn);
            throw new BusinessException("商户订单不存在");
        }
        if (OrderEnum.ORDER_STATUS_WAIT_GET_GOOD.getCode() != merchantOrder.getStatus()) {
            log.error("订单发货异常：order:{}", JSON.toJSONString(merchantOrder));
            throw new BusinessException("商户订单状态异常,无法确认发货");
        }
        //更新商户订单
        merchantOrderService.updateMerchantOrderWhenDelivery(orderSn, OrderEnum.ORDER_STATUS_HAS_SEND_GOOD.getCode());
        //更新用户订单
        orderService.updateOrderWhenDelivery(merchantOrder.getUserOrderSn(), OrderEnum.ORDER_STATUS_HAS_SEND_GOOD.getCode());
    }
}
